package com.itfreer.form.service.metadata;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.form.api.BaseRestService;
import com.itfreer.form.api.BaseService;
import com.itfreer.form.entity.metadata.MetadataEntity;
import com.itfreer.utils.json.JsonUtils;

/**
 * 定义书签功能接口
 */
@Component
@Path("/metadata/")
public class RestMetadataService extends BaseRestService<MetadataEntity> {

	@Autowired
	private MetadataService metadataService;

	@Override
	protected BaseService<MetadataEntity> getService() {
		return metadataService;
	}
	
	@Override
	protected String getServiceName() {
		return "metadata";
	}

	/**
	 * 根据metadata名称，获取所有元数据
	 * 
	 * @param metaDate
	 * @return
	 */
	@POST
	@Path("/getEntitys/{id:.+}")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public List<MetadataEntity> getEntitysByID(@PathParam("id") String metaData) {
		return metadataService.getEntitys(metaData);
	}

	/**
	 * 根据元数据，转义字典
	 * 
	 * @param metadata
	 * @param value
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@POST
	@Path("/dictionaryEscape/{id:.+}")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public Map<String, Object> dictionaryEscape(@PathParam("id") String metadata,
			@FormParam("value") String valueString) throws IOException {
		HashMap value = JsonUtils.toBean(valueString, HashMap.class);
		return metadataService.dictionaryEscape(metadata, value);
	}

	/**
	 * 根据元数据，转义字典
	 * 
	 * @param metadata
	 * @param value
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@POST
	@Path("/dictionaryEscapeEx")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public List<Map<String, Object>> dictionaryEscapeEx(String data) throws IOException {
		HashMap<String, Object> args = getRestParam(data);
		String metadata = "";
		String valuesString = "";
		if (args != null) {
			if (args.containsKey("id") && args.get("id") != null) {
				metadata = args.get("id").toString();
			}

			if (args.containsKey("values") && args.get("values") != null) {
				valuesString = args.get("values").toString();
			}
		}
		List dataList = (List) JsonUtils.toBean(valuesString, List.class);
		List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
		if (dataList != null) {
			for (Object valueString : dataList) {
				HashMap<String, Object> item = (HashMap) valueString;
				values.add(item);
			}
		}
		List<Map<String, Object>> result = metadataService.dictionaryEscapeEx(metadata, values);
		return result;
	}
}
